"""
分析任务模型
"""
from datetime import datetime
import json
from typing import Dict, Optional
from .. import db

class AnalysisTask(db.Model):
    """分析任务模型类"""
    __tablename__ = 'analysis_tasks'

    # 任务状态常量
    STATUS_PENDING = 'pending'
    STATUS_RUNNING = 'running'
    STATUS_COMPLETED = 'completed'
    STATUS_FAILED = 'failed'

    # 分析类型常量
    TYPE_KMEANS = 'kmeans'
    TYPE_DECISION_TREE = 'decision_tree'
    TYPE_LINEAR_REGRESSION = 'linear_regression'
    TYPE_PCA = 'pca'

    VALID_TYPES = [
        TYPE_KMEANS,
        TYPE_DECISION_TREE,
        TYPE_LINEAR_REGRESSION,
        TYPE_PCA
    ]

    id = db.Column(db.Integer, primary_key=True)
    dataset_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), nullable=False)
    
    # 任务信息
    task_type = db.Column(db.String(50), nullable=False)  # kmeans/regression等
    _parameters = db.Column('parameters', db.Text)  # 分析参数
    _result = db.Column('result', db.Text)  # 分析结果
    
    # 状态跟踪
    status = db.Column(db.String(20), default=STATUS_PENDING)
    error_message = db.Column(db.Text)  # 错误信息（如果失败）
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    started_at = db.Column(db.DateTime)
    completed_at = db.Column(db.DateTime)

    @property
    def parameters(self) -> Dict:
        """获取分析参数"""
        if self._parameters:
            return json.loads(self._parameters)
        return {}

    @parameters.setter
    def parameters(self, value: Dict):
        """设置分析参数"""
        if value is not None:
            self._parameters = json.dumps(value)
        else:
            self._parameters = None

    @property
    def result(self) -> Dict:
        """获取分析结果"""
        if self._result:
            return json.loads(self._result)
        return {}

    @result.setter
    def result(self, value: Dict):
        """设置分析结果"""
        if value is not None:
            self._result = json.dumps(value)
        else:
            self._result = None

    def start(self):
        """开始任务"""
        self.status = self.STATUS_RUNNING
        self.started_at = datetime.utcnow()
        from app import db
        db.session.commit()

    def complete(self, result: Dict):
        """
        完成任务
        
        Args:
            result: 分析结果
        """
        self.status = self.STATUS_COMPLETED
        self.result = result
        self.completed_at = datetime.utcnow()
        from app import db
        db.session.commit()

    def fail(self, error_message: str):
        """
        标记任务失败
        
        Args:
            error_message: 错误信息
        """
        self.status = self.STATUS_FAILED
        self.error_message = error_message
        self.completed_at = datetime.utcnow()
        from app import db
        db.session.commit()

    @classmethod
    def validate_task_type(cls, task_type: str) -> bool:
        """
        验证任务类型是否有效
        
        Args:
            task_type: 任务类型
            
        Returns:
            bool: 是否有效
        """
        return task_type in cls.VALID_TYPES

    def to_dict(self) -> Dict:
        """转换为字典格式"""
        return {
            'id': self.id,
            'dataset_id': self.dataset_id,
            'task_type': self.task_type,
            'parameters': self.parameters,
            'status': self.status,
            'error_message': self.error_message,
            'created_at': self.created_at.isoformat(),
            'started_at': self.started_at.isoformat() if self.started_at else None,
            'completed_at': self.completed_at.isoformat() if self.completed_at else None,
            'result': self.result
        }

    def __repr__(self):
        return f'<AnalysisTask {self.task_type} on Dataset {self.dataset_id}>' 